import React from 'react'
import { connect } from 'dva'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import AddEndContractModal from './AddEndContractModal'
import AddNeedDesignContractModal from './AddNeedDesignContractModal'
import AddNoDesignContractModal from './AddNoDesignContractModal'
import ConfirmDesignModal from './ConfirmDesignModal'
import QuoteOrderModal from './QuoteOrderModal'
import ConfirmQuoteModal from './ConfirmQuoteModal'
import PublishEndOrderModal from './PublishEndOrderModal'
import PublishCustomizeOrderModal from './PublishCustomizeOrderModal'
import PublishAgainCustomizeOrderModal from './PublishAgainCustomizeOrderModal'
import CancelModal from './CancelModal'
import DoDesignModal from './DoDesignModal'
import { Page } from 'components'
import { LwjDialog } from 'components'
import DescriptionList from 'components/DescriptionList'
import { Card, Table, Tag, Divider, Button, Menu, Dropdown, Icon, Modal } from 'antd'
import styles from './index.less'
import moment from 'moment'
import {
  contractOrderType,
  productType,
  contractOrderStatus,
  contractActionType,
  contractCancelStatus,
  contractChangeStatus,
  breakStatus,
  purchaseType4Special
} from 'utils/enumConfig'
import { LwjDownload } from 'components'
import ContractDetailModal from './ContractDetailModal'
import MaterialModal from './MaterialModal'
import { showButton } from 'utils/promissionFilter'
import { checkIsStoreRoles } from 'utils/enumConfig'
import PayOrderPublishModal from './PayOrderPublishModal';
import { purchaseType } from 'utils/enumConfig';

const { Description } = DescriptionList

const UpdateContractOrder = ({ location, dispatch, updateContractOrder, contractOrders, orderCancel, app, loading }) => {

  let {
    currentOrderDetail,
    currentSystemProperty,
    isShowAddEndContractModal,
    isShowNeedDesignContractModal,
    isShowNoDesignContractModal,
    isUpdate,
    currentContractDetail,
    isDesignNeeded,
    isShowConfirmDesignModal,
    isShowQuoteModal,
    isShowConfirmQuoteModal,
    isShowPublishEndOrderModal,
    isShowPublishCustomizeOrderModal,
    isShowDoDesignModal,
    listState,
    isShowPublishAgainCustomizeOrderModal,
    isShowContractDetailModal,
    confirmAddLoading,
    isPushOmsModel,
    currentRefreshRecordId,
    payOrderList,
    isShowPayOrderPushModal,
    currentPayOrder,
    commodities,
    material: {
      modalVisible: materialModalVisible,
      selectedKeys: materialSelectedKeys,
      selectedItems: materialSelectedItems,
      items: materialItems,
      pagination: materialPagination,
      typeTree: materialTypeTree,
      treeSearchKeyword: materialTreeSearchKeyword,
      typeItem: materialTypeItem
    },
  } = updateContractOrder

  const {
    currentItem: contractItem,
    createModalVisible: contractCreateModalVisible,
  } = orderCancel

  let { user, resources } = app

  // 判断当前角色
  let roles = user.roles
  let currentUserRole = ''
  if (_.findIndex(roles, { 'name': 'ROLE_ADMIN' }) > -1) {
    currentUserRole = 'ROLE_ADMIN'
  } else if (_.findIndex(roles, { 'name': 'ROLE_DESIGNER' }) > -1) {
    currentUserRole = 'ROLE_DESIGNER'
  } else if (_.findIndex(roles, { 'name': 'ROLE_SALESMAN' }) > -1) {
    currentUserRole = 'ROLE_SALESMAN'
  }

  const isLoaded = !_.isEmpty(currentOrderDetail)

  const breadcrumbList = [
    {
      title: '订单管理',
      href: `/orderList/${listState}`
    }, {
      title: listState === 'ALL' ? '全部订单' : '我的订单',
      href: `/orderList/${listState}`
    }, {
      title: '修改合同订单'
    }
  ]

  const refreshFromOms = (record) => {
    dispatch({
      type: 'updateContractOrder/setCurrentRefreshRecordId',
      payload: record.id
    })
    dispatch({
      type: 'updateContractOrder/refreshFromOms',
      payload: record
    })
  }

  const onShowContractDetail = (record) => {
    dispatch({
      type: 'updateContractOrder/onShowContractDetail',
      payload: {
        contractOrderId: record.id,
        salesOrderId: record.salesOrderId
      }
    })
  }
  const isShowFreshButton = (record) => {
    const status = record.status
    return status === "PUBLISHED" || status === "OMS_FACTORY_AUDIT_FAILED" || status === "PENDING_CONFIRM_OMS_QUOTED" || status === "PUBLISHED_TO_OMS"
  }
  const contractOrderColumnsBegin = [
    {
      title: '合同号',
      dataIndex: 'contractNum',
      key: 'contractNum',
      width: 150,
      render: (text, record, index) => (
        <span>
          <a className={styles.a} onClick={() => onShowContractDetail(record)}>{record.contractNum}</a>
          <Button
            onClick={() => onShowContractDetail(record)}
            size="small"
            shape="circle"
            icon="search"
            style={{ marginLeft: 5 }} />
        </span>

      )
    }, {
      title: '合同类型',
      dataIndex: 'contractOrderType',
      key: 'contractOrderType',
      width: 100,
      render: (text, record, index) => (contractOrderType[record.contractOrderType])
    }, {
      title: '产品类型',
      dataIndex: 'productType',
      key: 'productType',
      width: 100,
      render: (text, record, index) => (productType[record.productType])
    }, {
      title: '是否需要设计',
      dataIndex: 'designNeeded',
      key: 'designNeeded',
      width: 100,
      render: (text, record, index) => (record.designNeeded ? '是' : '否')
    }, {
      title: '采购方式',
      dataIndex: 'purchaseType',
      key: 'purchaseType',
      width: 100,
      render: (text, record, index) => (currentSystemProperty.purchaseTypeCheck ?
        purchaseType[text] : purchaseType4Special[text])
    }

  ]

  const buildContractOrderStatus = (record) => {
    return record.contractCancelStatus === 'NULL' ? record.changeStatus === 'NULL' || record.changeStatus === null ? contractOrderStatus[record.status] : contractChangeStatus[record.changeStatus] : contractCancelStatus[record.contractCancelStatus]
  }
  console.log(loading)
  const contractOrderColumnsEnd = [{
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    render: (text, record, index) => (
      <div>
        {buildContractOrderStatus(record)}
        {_.isArray(user.roles) && user.roles.some((element) => {
          return element.name === 'ROLE_ADMIN'
        }) && isShowFreshButton(record) && <Button
            onClick={() => refreshFromOms(record)}
            size="small"
            shape="circle"
            icon="reload"
            loading={loading.global && record.id === currentRefreshRecordId}
            style={{ marginLeft: 5 }} />}
      </div>
    )
  }, {
    title: '操作',
    dataIndex: 'handleType',
    key: 'handleType',
    width: 150,
    render: (text, record, index) => {
      let button = record.contractActionTypes.length > 0 ?
        record.contractActionTypes.map((item, key) => {
          return (
            record.contractCancelStatus === 'NULL' && record.changeStatus !== 'CHANGING' &&
            <span key={key}>
              <a onClick={() => updateContract(item, record)}>{contractActionType[item]}</a>
              {record.canCancel && record.changeStatus !== 'CHANGING' && record.contractActionTypes.length - 1 === key && record.status !== 'PUBLISHED' &&
                <Divider type="vertical" />}
              {!record.isFromThirdPart && record.canCancel && record.changeStatus !== 'CHANGING' && record.contractActionTypes.length - 1 === key &&
                <a onClick={() => {
                  dispatch({
                    type: 'orderCancel/showCreateModal',
                    payload: record
                  })
                }}>取消</a>}
              {record.contractActionTypes.length - 1 !== key && <Divider type="vertical" />}
            </span>
          )
        }) : record.canCancel && record.changeStatus !== 'CHANGING' && <a key={0} onClick={() => {
          dispatch({ type: 'orderCancel/showCreateModal', payload: record })
        }}>取消</a>

      let designButton = (
        <a key={1} onClick={() => updateContract('DESIGN', record)}>{contractActionType['DESIGN']}</a>)
      const userRoles = user.roles || []
      let filterUserRoles = userRoles.filter(item => item.name === 'ROLE_STORE_EMPLOYEE' || item.name === 'ROLE_STORE_ADMIN')

      if (filterUserRoles.length > 0 && record.status === 'DENIED_DESIGN') {
        if (!Array.isArray(button)) {
          button = [button]
          button.push((<Divider key={100} type="vertical" />))
          button.push(designButton)
        }
      }

      return button
    }
  }]
  const contractDetailModalProps = {
    title: '合同详情',
    visible: isShowContractDetailModal,
    destroyOnClose: true,
    width: 1000,
    currentContractDetail,
    footer: null,
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideContractDetailModal',
        payload: {}
      })
    },
    resources,
    user,
  }

  // 创建|修改成品合同 props
  const addEndContractModalProps = {
    visible: isShowAddEndContractModal,
    title: isUpdate ? '修改成品合同' : '添加成品合同',
    destroyOnClose: true,
    isUpdate,
    width: 1000,
    currentContractDetail,
    currentOrderDetail,
    currentSystemProperty,
    user,
    onOk(record) {
      dispatch({
        type: 'updateContractOrder/goOrderSalesmarket',
        item: record,
        salesDistributorId: currentOrderDetail.salesDistributorId
      })
      dispatch({
        type: 'updateContractOrder/hideAddContractModal',
        payload: {}
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideAddContractModal',
        payload: {}
      })
    }
  }

  let addCustomizeContractModalTitle = isUpdate ? '修改定制合同' : '添加定制合同'
  addCustomizeContractModalTitle = addCustomizeContractModalTitle + (isDesignNeeded ? '（需要设计）' : '（不需要设计）')
  // 创建|修改定制合同 props
  const addCustomizeContractModalProps = {
    title: addCustomizeContractModalTitle,
    destroyOnClose: true,
    isDesignNeeded,
    isUpdate,
    loading,
    width: 1000,
    currentOrderDetail,
    currentContractDetail,
    currentUserRole,
    confirmLoading: loading.effects['updateContractOrder/addContractOrder'] ||
      loading.effects['updateContractOrder/updateContractOrder'],
    onOk(record) {
      if (!confirmAddLoading) {
        dispatch({
          type: 'updateContractOrder/setAddLoading',
          payload: { confirmAddLoading: true }
        })
        if (isUpdate) {
          dispatch({
            type: 'updateContractOrder/updateContractOrder',
            payload: { contractOrder: record }
          })
        } else {
          dispatch({
            type: 'updateContractOrder/addContractOrder',
            payload: { contractOrder: record }
          })
        }
        setTimeout(() => {
          dispatch({
            type: 'updateContractOrder/setAddLoading',
            payload: { confirmAddLoading: false }
          })
        }, 2000)
      }
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideAddContractModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消'
  }

  // 上传设计方案 props
  const doDesignModalProps = {
    visible: isShowDoDesignModal,
    title: '上传设计方案',
    destroyOnClose: true,
    currentContractDetail,
    confirmLoading: loading.effects['updateContractOrder/doDesign'],
    width: 1000,
    onOk(values) {
      dispatch({
        type: 'updateContractOrder/doDesign',
        payload: { doDesignInfo: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideDoDesignModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消'
  }

  // 确认设计方案 props
  const confirmDesignModalProps = {
    visible: isShowConfirmDesignModal,
    title: '确认设计方案',
    destroyOnClose: true,
    currentContractDetail,
    footer: null,
    isAcceptLoading: loading.effects['updateContractOrder/acceptDesign'],
    isDenyLoading: loading.effects['updateContractOrder/denyDesign'],
    width: 1000,
    acceptDesign() {
      dispatch({
        type: 'updateContractOrder/acceptDesign',
        payload: {}
      })
    },
    denyDesign(values) {
      dispatch({
        type: 'updateContractOrder/denyDesign',
        payload: { denyParams: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideConfirmDesignModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消'
  }

  // 合同报价 props
  const quoteModalProps = {
    visible: isShowQuoteModal,
    title: '合同报价',
    destroyOnClose: true,
    currentContractDetail,
    width: 1000,
    confirmLoading: loading.effects['updateContractOrder/quoteOrder'],
    onOk(values) {
      dispatch({
        type: 'updateContractOrder/quoteOrder',
        payload: { quoteInfo: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideQuoteModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消',
    isFromThirdPart: _.isEmpty(currentOrderDetail.sourceOrderNum) ? false : true
  }

  // 确认报价方案 props
  const confirmQuoteModalProps = {
    visible: isShowConfirmQuoteModal,
    title: '确认报价方案',
    destroyOnClose: true,
    currentContractDetail,
    isAcceptLoading: loading.effects['updateContractOrder/acceptQuote'],
    isDenyLoading: loading.effects['updateContractOrder/denyQuote'],
    footer: null,
    width: 1000,
    dispatch,
    acceptQuote() {
      LwjDialog.confirm({
        title: '确认支付',
        content:
          <div>
            <span>
              <label>合同金额：</label> {currentContractDetail.orderQuoteSummary.orderAmount.toFixed(2)}
            </span><br />
            <span>
              <label>应付金额：</label> {currentContractDetail.orderQuoteSummary.orderAmount < currentContractDetail.balance ? (currentContractDetail.orderQuoteSummary.orderAmount).toFixed(2) : (currentContractDetail.balance).toFixed(2)}
            </span><br />
            <span>
              <label>账户余额：</label> {currentContractDetail.balance.toFixed(2)}
            </span><br />
          </div>,
        okText: '确认',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: 'updateContractOrder/acceptQuote',
            payload: {}
          })
        },
        onCancel() { }
      })
    },
    denyQuote(values) {
      dispatch({
        type: 'updateContractOrder/denyQuote',
        payload: { denyParams: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hideConfirmQuoteModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消'
  }

  /**
   * 为物料编码增加index，方便之后定位每一个参数
   * @param {*} materielItems
   */
  const materielItemsIndex = (materielItems) => {
    let index = 1
    for (let item of materielItems) {
      item.index = index
      index++
    }
  }

  // 推送成品到OMS props
  const publishEndOrderModalProps = {
    visible: isShowPublishEndOrderModal,
    title: '成品订单推送',
    destroyOnClose: true,
    currentContractDetail,
    isPushOmsModel,
    isLoading: loading.effects['updateContractOrder/publishToOms'],
    footer: null,
    wrapClassName: 'vertical-center-modal',
    width: 1000,
    dispatch,
    toChangeOrder() {
      dispatch({
        type: 'updateContractOrder/toChangeOrder',
        payload: {}
      })
    },
    onOk(values) {
      dispatch({
        type: 'updateContractOrder/publishToOms',
        payload: { publishOrderInfo: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hidePublishEndOrderModal',
        payload: {}
      })
    },
    onAddMaterielItem() {
      dispatch({
        type: 'updateContractOrder/showMaterialModalVisible',
        payload: {}
      })
      dispatch({
        type: 'updateContractOrder/getMaterialType',
        payload: {}
      })
    },
    onMaterielItemChange(value, record, column) {
      if (column === 'quantity' && _.isNaN(Number(value))) {
        Modal.info({ title: '提示', content: `物料数量必须为大于0的数字` })
        return
      }
      currentContractDetail
        .materielItems
        .filter(item => item.index === record.index)
        .map(item => item[column] = value)
      dispatch({
        type: 'updateContractOrder/setCurrentContractDetail',
        payload: {
          currentContractDetail
        }
      })
    },
    onDeleteMaterielItem(record) {
      _.remove(currentContractDetail.materielItems, (n) => {
        return n.index === record.index
      })
      materielItemsIndex(currentContractDetail.materielItems)
      dispatch({
        type: 'updateContractOrder/setCurrentContractDetail',
        payload: {
          currentContractDetail
        }
      })
    },
    okText: '确认',
    cancelText: '取消'
  }
  const payOrderPushModalProps = {
    visible: isShowPayOrderPushModal,
    title: '待支付订单',
    destroyOnClose: true,
    currentPayOrder,
    isPushOmsModel,
    currentOrderDetail,
    isLoading: loading.global,
    footer: null,
    wrapClassName: 'vertical-center-modal',
    width: 1500,
    dispatch,
    currentSystemProperty,
    commodities,
    toChangeOrder() {
      dispatch({
        type: 'updateContractOrder/toChangeOrder',
        payload: {}
      })
    },
    onOk(values) {
      dispatch({
        type: 'updateContractOrder/publishToOms',
        payload: { publishOrderInfo: values }
      })
      dispatch({
        type: 'updateContractOrder/getOrderDetail',
        payload: {
          orderId: currentOrderDetail.id
        }
      })
      dispatch({
        type: 'updateContractOrder/listAllPayOrder', payload: currentOrderDetail.id
      })
    },
    onCancel() {
      dispatch({
        type: 'updateContractOrder/setIsShowPayOrderPushModal',
        payload: false
      })
      debugger;
      dispatch({
        type: 'updateContractOrder/getOrderDetail',
        payload: {
          orderId: currentOrderDetail.id
        }
      })
      dispatch({
        type: 'updateContractOrder/listAllPayOrder', payload: currentOrderDetail.id
      })
    },
    onAddMaterielItem() {
      dispatch({
        type: 'updateContractOrder/showMaterialModalVisible',
        payload: {}
      })
      dispatch({
        type: 'updateContractOrder/getMaterialType',
        payload: {}
      })
    },
    onMaterielItemChange(value, record, column) {
      if (column === 'quantity' && _.isNaN(Number(value))) {
        Modal.info({ title: '提示', content: `物料数量必须为大于0的数字` })
        return
      }
      currentContractDetail
        .materielItems
        .filter(item => item.index === record.index)
        .map(item => item[column] = value)
      dispatch({
        type: 'updateContractOrder/setCurrentContractDetail',
        payload: {
          currentContractDetail
        }
      })
    },
    onDeleteMaterielItem(record) {
      _.remove(currentContractDetail.materielItems, (n) => {
        return n.index === record.index
      })
      materielItemsIndex(currentContractDetail.materielItems)
      dispatch({
        type: 'updateContractOrder/setCurrentContractDetail',
        payload: {
          currentContractDetail
        }
      })
    },
    okText: '确认',
    cancelText: '取消'
  }
  const materialModalProps = {
    title: '添加物料',
    visible: materialModalVisible,
    confirmLoading: false,
    destroyOnClose: true,
    width: 1200,
    dispatch,
    onOk: () => {
      if (_.isEmpty(currentContractDetail.materielItems)) {
        currentContractDetail.materielItems = []
      }
      materialSelectedItems.forEach(item => {
        let index = currentContractDetail.materielItems.findIndex(element => item.stockNumber === element.code)

        if (index < 0) {
          currentContractDetail
            .materielItems
            .push({ 'code': item.stockNumber, name: item.name, 'quantity': '' })
        }
      })

      materielItemsIndex(currentContractDetail.materielItems)
      dispatch({
        type: 'updateContractOrder/addMaterielItem',
        payload: {
          currentContractDetail
        }
      })
      dispatch({
        type: 'updateContractOrder/hideMaterialModalVisible',
        payload: {}
      })
      dispatch({
        type: 'updateContractOrder/clearMaterialTypeTree',
        payload: {}
      })
    },
    onCancel: () => {
      dispatch({
        type: 'updateContractOrder/hideMaterialModalVisible',
        payload: {}
      })
      dispatch({
        type: 'updateContractOrder/setSearchKeyword',
        payload: { keyword: '' }
      })
      dispatch({
        type: 'updateContractOrder/clearMaterialTypeTree',
        payload: {}
      })
    },
    materialTypeItem,
    tableProps: {
      dataSource: materialItems,
      pagination: materialPagination,
      pageChangeAction: 'updateContractOrder/getMaterialList',
      loading: loading.effects['updateContractOrder/getMaterialList'],
      selectedRowKeys: materialSelectedKeys,
      selectType: 'multiple',
      dispatch,
      onSelectRows: (ids, data) => {
        dispatch({
          type: 'updateContractOrder/setMaterialSelected',
          payload: {
            keys: ids,
            items: data
          }
        })
      },
    },
    treeProps: {
      dataSource: materialTypeTree,
      defaultExpandAll: false,
      showLine: true,
      showIcon: false,
      onSelect: (datum) => {
        dispatch({
          type: 'updateContractOrder/setTypeItem',
          payload: datum
        })
        dispatch({
          type: 'updateContractOrder/getMaterialList',
          payload: {
            productTypeId: datum.id
          }
        })
      },
      dispatch,
      searchKeyword: materialTreeSearchKeyword,
    }
  }

  // 推送定制品到OMS props
  const publishCustomizeOrderModalProps = {
    visible: isShowPublishCustomizeOrderModal,
    title: '定制订单推送',
    destroyOnClose: true,
    currentContractDetail,
    wrapClassName: 'vertical-center-modal',
    width: 1000,
    isLoading: loading.effects['updateContractOrder/publishToOms'],
    dispatch,
    footer: null,
    toChangeOrder() {
      dispatch({
        type: 'updateContractOrder/toChangeOrder',
        payload: {}
      })
    },
    onOk(values) {
      dispatch({
        type: 'updateContractOrder/publishToOms',
        payload: { publishOrderInfo: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hidePublishCustomizeOrderModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消'
  }

  // 再次推送定制品合同到OMS props
  const publishAgainCustomizeOrderModalProps = {
    visible: isShowPublishAgainCustomizeOrderModal,
    title: '再次推送到OMS（定制品）',
    destroyOnClose: true,
    currentContractDetail,
    wrapClassName: 'vertical-center-modal',
    width: 1000,
    confirmLoading: loading.effects['updateContractOrder/publishAgain'],
    dispatch,
    onOk(values) {
      dispatch({
        type: 'updateContractOrder/publishAgain',
        payload: { publishOrderInfo: values }
      })
    },
    onCancel(record) {
      dispatch({
        type: 'updateContractOrder/hidePublishAgainCustomizeModal',
        payload: {}
      })
    },
    okText: '确认',
    cancelText: '取消'
  }

  const cancelModalProps = {
    visible: contractCreateModalVisible,
    dispatch,
    currentItem: contractItem
  }

  /**
   * 合同操作
   * @param {*} contractActionType
   * @param {*} record
   */
  const updateContract = (contractActionType, record) => {
    if (contractActionType === 'EDIT') {
      dispatch({
        type: 'updateContractOrder/toUpdateContract',
        payload: { contractOrder: record }
      })
    }
    if (contractActionType === 'PLACE_ORDER') {
      LwjDialog.confirm({
        title: '您确认要提交吗？',
        content: '提交后，将无法删除和修改合同信息',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: 'updateContractOrder/placeOrder',
            payload: {
              contractOrderId: record.id,
              version: record.version
            }
          })
        },
        onCancel() { }
      })
    }
    if (contractActionType === 'DESIGN') {
      dispatch({
        type: 'updateContractOrder/toDoDesign',
        payload: { contractOrder: record }
      })
    }
    if (contractActionType === 'DELETE') {
      LwjDialog.confirm({
        title: '您确认要删除该合同吗？',
        content: '删除后，合同数据将无法恢复',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: 'updateContractOrder/deleteContract',
            payload: { contractOrderId: record.id }
          })
        },
        onCancel() { }
      })
    }
    if (contractActionType === 'CONFIRM_DESIGN') {
      dispatch({
        type: 'updateContractOrder/toConfirmDesign',
        payload: { contractOrder: record }
      })
    }
    if (contractActionType === 'QUOTE') {
      dispatch({
        type: 'updateContractOrder/toQuote',
        payload: { contractOrder: record }
      })
    }
    if (contractActionType === 'CONFIRM_QUOTE') {
      dispatch({
        type: 'updateContractOrder/toConfirmQuote',
        payload: { contractOrder: record }
      })
    }
    if (contractActionType === 'PUBLISH') {
      dispatch({
        type: 'updateContractOrder/toPublishToOms',
        payload: { contractOrder: record }
      })
      dispatch({
        type: 'updateContractOrder/isPushOms',
        payload: {
          isPushOms: true,
        }
      })
    }
    if (contractActionType === 'PUBLISH_AGAIN') {
      dispatch({
        type: 'updateContractOrder/toPublishAgain',
        payload: { contractOrder: record }
      })
    }
  }

  const toCreateContract = (e) => {
    if (e.key === 'END') {
      dispatch({
        type: 'updateContractOrder/toCreateEndContract',
        payload: {}
      })
    }
    if (e.key === 'NEED_TO_DESIGN') {
      dispatch({
        type: 'updateContractOrder/showNeedDesignContractModal',
        payload: { isDesignNeeded: true }
      })
    }
    if (e.key === 'NO_DESIGN_REQUIRED') {
      dispatch({
        type: 'updateContractOrder/showNoDesignContractModal',
        payload: { isDesignNeeded: false }
      })
    }
  }

  const menu = (
    <Menu onClick={toCreateContract}>
      <Menu.Item key="NEED_TO_DESIGN">定制且需要设计</Menu.Item>
      <Menu.Item key="NO_DESIGN_REQUIRED">定制不需要设计</Menu.Item>
      <Menu.Item key="END">成品</Menu.Item>
    </Menu>
  )

  const isProject = currentOrderDetail.salesOrderType === 'PROJECT'

  const contractColumn = checkIsStoreRoles(app.user) ? contractOrderColumnsBegin.concat(contractOrderColumnsEnd) : contractOrderColumnsBegin.concat(contractOrderColumnsEnd)
  // const buildColumn = () => {
  //   if(!checkIsStoreRoles(app.user)){
  //     contractOrderColumnsBegin.push(notStore)
  //   }
  //   contractColumn =  contractOrderColumnsBegin.concat(contractOrderColumnsEnd)
  // }

  // console.info(buildColumn)
  const buildPic = (record) => {
    const picArray = new Array(0);
    const contractSummaries = record.contractGoodsSnapshotSummaries;
    if (_.isArray(contractSummaries)) {
      contractSummaries.forEach(element => {
        element.coverPics.forEach(pic => {
          picArray.push(pic)
        })
      });
    }
    return picArray;
  }


  const payOrderColumn = [
    {
      title: '订单号',
      dataIndex: 'orderNum',
      key: 'orderNum',
      width: "10%"
    },
    {
      title: '合同编号',
      dataIndex: 'contractGoodsSnapshotSummaries',
      key: 'contractGoodsSnapshotSummaries',
      width: "20%",
      render: (text, record) => {
        return (record.contractGoodsSnapshotSummaries ? record.contractGoodsSnapshotSummaries.map((val, index) => <div key={index}>{val.contractNum}</div>) : '无')
      }
    }, {
      title: '收货人姓名',
      dataIndex: 'consigneeName',
      key: 'consigneeName',
      width: "10%",
      render: (text, record, index) => (record.consigneeName + "; " + record.consigneePhoneNum)
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: "15%",
      render: (text, record, index) => (moment(record.createTime).format("YYYY-MM-DD"))
    },
    {
      title: '支付时间',
      dataIndex: 'paidAt',
      key: 'paidAt',
      width: "15%",
      render: (text, record, index) => (moment(record.paidAt).format("YYYY-MM-DD") === 'Invalid date' ? '无' : moment(record.paidAt).format("YYYY-MM-DD HH:mm:ss"))

    },
    {
      title: '拆分状态',
      dataIndex: 'breakStatus',
      key: 'breakStatus',
      width: "15%",
      render: (text, record, index) => (breakStatus[text])
    },
    {
      title: '操作',
      key: 'handle',
      width: "15%",
      render: (text, record) => (
        record.breakStatus !== 'BREAKED' && <span>
          <a onClick={() => {
            dispatch({
              type: 'updateContractOrder/setIsShowPayOrderPushModal',
              payload: true
            })
            dispatch({
              type: 'updateContractOrder/initPurchaseType'
            })
            dispatch({
              type: 'updateContractOrder/setCurrentPayOrder',
              payload: record
            })
          }}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => {
            Modal.confirm({
              title: '确定吗？',
              content: '确定要取消该支付订单吗？',
              onOk: () => {
                dispatch({
                  type: 'updateContractOrder/cancelPayOrder',
                  payload: record.id
                })
              }

            })
          }}>取消</a>
        </span>
      )
    }
  ];

  const expandedRowRender = (record) => {
    let _imgs = buildPic(record).map((val,index) => <img alt="" className={styles.imgGap} src={val} height={60} width={60} key={index} />);
    return <div style={{ margin: 0 }} key="img">{_imgs}</div>;
  }

  return (
    <PageHeaderLayout title="修改合同订单" breadcrumbList={breadcrumbList}>
      <ContractDetailModal {...contractDetailModalProps} />
      {isLoaded && <Page inner>
        <AddEndContractModal {...addEndContractModalProps} />
        <AddNeedDesignContractModal visible={isShowNeedDesignContractModal} {...addCustomizeContractModalProps} />
        <AddNoDesignContractModal visible={isShowNoDesignContractModal} {...addCustomizeContractModalProps} />
        <ConfirmDesignModal {...confirmDesignModalProps} />
        <QuoteOrderModal {...quoteModalProps} />
        <ConfirmQuoteModal {...confirmQuoteModalProps} />
        <PublishEndOrderModal {...publishEndOrderModalProps} />
        <PayOrderPublishModal {...payOrderPushModalProps} />
        <PublishCustomizeOrderModal {...publishCustomizeOrderModalProps} />
        <DoDesignModal {...doDesignModalProps} />
        <PublishAgainCustomizeOrderModal {...publishAgainCustomizeOrderModalProps} />
        {materialModalVisible && <MaterialModal {...materialModalProps} />}
        {contractCreateModalVisible && <CancelModal {...cancelModalProps} />}
        <Card className={styles.card} bordered={false}>
          <div className={styles.title}>合同信息</div>
          {showButton('orderList.contract.add', resources, user) && !currentOrderDetail.isFromThirdPart && <Dropdown overlay={menu}>
            <Button
              type="primary"
              style={{ marginRight: 10, marginBottom: 10 }}>新增合同<Icon type="down" /></Button>
          </Dropdown>}
          <Table
            style={{ marginBottom: 24 }}
            pagination={false}
            bordered
            dataSource={currentOrderDetail.contractOrderSummaries}
            columns={contractColumn}
            rowKey="id" />
          <Divider style={{ marginBottom: 32 }} />
          <div className={styles.title}>支付订单信息</div>
          <Table
            style={{ marginBottom: 24 }}
            pagination={false}
            dataSource={payOrderList}
            columns={payOrderColumn}
            defaultExpandAllRows={true}
            expandedRowRender={expandedRowRender}
            rowKey="id" />
          <Divider style={{ marginBottom: 32 }} />
          <DescriptionList
            size="small"
            title={(<div>
              意向单基本信息 {isProject && <Tag color="#f50">工程订单</Tag>}
            </div>)}
            style={{ marginBottom: 32 }}>
            <Description term="订单编号">{currentOrderDetail.num}</Description>
            {currentOrderDetail.sourceOrderNum && <Description term="第三方单号">{currentOrderDetail.sourceOrderNum}</Description>}
            <Description term="创建时间">{moment(currentOrderDetail.createTime).format('YYYY-MM-DD HH:mm:ss')}</Description>
            <Description term="所属门店">{currentOrderDetail.salesDistributorName}</Description>
          </DescriptionList>
          <Divider style={{ marginBottom: 32 }} />
          <DescriptionList
            size="small"
            title="客户信息"
            style={{ marginBottom: 32 }}>
            <Description term="客户姓名">{currentOrderDetail.customerName}</Description>
            <Description term="客户手机号">{currentOrderDetail.customerPhoneNum}</Description>
            <Description term="客户地址">
              {!_.isEmpty(currentOrderDetail.customerProvince)
                && !_.isEmpty(currentOrderDetail.customerCity)
                && !_.isEmpty(currentOrderDetail.customerDistrict) ? currentOrderDetail.customerProvince.name
                + currentOrderDetail.customerCity.name
                + currentOrderDetail.customerDistrict.name
                + currentOrderDetail.customerAddress : '无'}
            </Description>
            <Description term="收货人姓名">{currentOrderDetail.consigneeName}</Description>
            <Description term="收货人手机号">{currentOrderDetail.consigneePhoneNum}</Description>
            <Description term="收货人地址">
              {!_.isEmpty(currentOrderDetail.consigneeProvince)
                && !_.isEmpty(currentOrderDetail.consigneeCity)
                && !_.isEmpty(currentOrderDetail.consigneeDistrict) ? currentOrderDetail.consigneeProvince.name
                + currentOrderDetail.consigneeCity.name
                + currentOrderDetail.consigneeDistrict.name
                + currentOrderDetail.consigneeAddress : '无'}
            </Description>
          </DescriptionList>
          <Divider style={{ marginBottom: 32 }} />
          <DescriptionList
            size="small"
            title="销售信息"
            style={{ marginBottom: 32 }}>
            <Description term="销售员">{currentOrderDetail.salesmanName}</Description>
            <Description term="意向产品说明">{currentOrderDetail.desireProductMemo}</Description>
            <Description term="参与活动说明">{currentOrderDetail.saleEvents}</Description>
            <Description term="备注信息">{currentOrderDetail.memo}</Description>
            <Description term="意向产品清单">{<LwjDownload title={'点击下载'}
              targetUrl={currentOrderDetail.desireProductsAttachment} />}</Description>
          </DescriptionList>
        </Card>
      </Page>}
    </PageHeaderLayout>
  )
}

export default connect(({ updateContractOrder, contractOrders, orderCancel, app, loading }) => ({
  updateContractOrder,
  contractOrders,
  orderCancel,
  app,
  loading
}))(UpdateContractOrder)
